//
//  PatrolInspectionVC.swift
//  Employee
//
//  Created by swordjoy on 2017/3/24.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import SwiftyJSON
import Moya

class PatrolInspectionVC: BaseVC {
  
  fileprivate var inspections: [Inspection] = []
  
  fileprivate lazy var noDataV: NoDataV = {
    
    let frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.noNavBarHeight - 100.adaptor)
    let view = NoDataV(frame: frame)
    view.topTipText = "太好啦~"
    view.bottomTipText = "今天没有巡检工作!"
    view.image = UIImage(named: "bg-01")!
    return view
    
  }()
  
  fileprivate var page = 0
  fileprivate var swipeLeft: UISwipeGestureRecognizer!
  fileprivate var swipeRight: UISwipeGestureRecognizer!
  
  fileprivate var calendarV: SJCalendar!
  
  fileprivate var tableView: UITableView!
  
  fileprivate var cancle: Cancellable?
  
  fileprivate var currentDate = Date()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = GlobalConfig.BGWhiteColor
    title = "移动巡检"
  
    create()
    gesture()
    pullData()
    
    GlobalConfig.notificationCenter.addObserver(self, selector: #selector(pullData), name: Notification.Name.inspection.updateFunctionTodayInspection, object: nil)
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    navigationController?.navigationBar.setBackgroundImage(GlobalConfig.BGWhiteImage, for: .default)
    navigationController?.navigationBar.titleTextAttributes = GlobalConfig.NavBarStackTitleAttributes
    
    GlobalConfig.baiduStatisticsPageViewStart("移动巡检")
  }
  
  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    
    GlobalConfig.baiduStatisticsPageViewEnd("移动巡检")
  }
  
  deinit {
    
    if let temp = cancle { temp.cancel() }
    GlobalConfig.notificationCenter.removeObserver(self)
  }

}

// MARK: - action

extension PatrolInspectionVC {
  @objc fileprivate func swipeLeft(_ swipe: UISwipeGestureRecognizer) {
    tableView.layer.sj.pushAnimation(0.5, direction: .right)
    currentDate = currentDate.add(components: [.day : 1])
    calendarV.selectedDate = currentDate.inLocalRegion()
    pullData()
  }
  
  @objc fileprivate func swipeRight(_ swipe: UISwipeGestureRecognizer) {
    tableView.layer.sj.pushAnimation(0.5)
    currentDate = currentDate.add(components: [.day : -1])
    calendarV.selectedDate = currentDate.inLocalRegion()
    pullData()
  }
}

// MARK: - fileprivate

extension PatrolInspectionVC {
  
  fileprivate func noData() {
    self.tableView.addSubview(self.noDataV)
  }
  
  @objc fileprivate func pullData() {
    // 先清空
    self.inspections = []
    tableView.reloadData()
    
    // 取消上次
    if let temp = cancle { temp.cancel() }
    
    let date = currentDate.inLocalRegion().string(custom: "yyyy-MM-dd")
    
    cancle = WorkorderRequest.shared.getInspectionPlans(date: date, success: { (inspections) in
      
      if inspections.isEmpty {
        self.noData()
        return
      } else {
        if let _ = self.noDataV.superview { self.noDataV.removeFromSuperview() }
      }
      
      self.inspections = inspections
      self.tableView.reloadData()
      
    })
    
  }
  
  @objc fileprivate func headerRefresh() {
    
    let date = currentDate.inLocalRegion().string(custom: "yyyy-MM-dd")
    
    cancle = WorkorderRequest.shared.getInspectionPlans(date: date, success: { (inspections) in
      
      
    })
    
    cancle = WorkorderRequest.shared.getInspectionPlans(date: date, success: { (inspections) in
      self.tableView.mj_header.endRefreshing()
      if inspections.isEmpty {
        self.noData()
        return
      }
      else { if let _ = self.noDataV.superview { self.noDataV.removeFromSuperview() } }
      self.inspections = inspections
      self.tableView.reloadData()
      
    }, failure: { 
      self.tableView.mj_header.endRefreshing()
    })
  }
  
  fileprivate func gesture() {
    swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swipeLeft(_:)))
    swipeLeft.direction = .left
    tableView.addGestureRecognizer(swipeLeft)
    
    let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swipeRight(_:)))
    swipeRight.direction = .right
    tableView.addGestureRecognizer(swipeRight)
  }
  
  fileprivate func create() {
    
    addBackItem()
    
    let calendarFrame = CGRect(x: 0, y: 0, width: UIScreen.width, height: 100)
    calendarV = SJCalendar(frame: calendarFrame)
    calendarV.delegete = self
    view.addSubview(calendarV)
    
    tableView = UITableView()
    tableView.backgroundColor = UIColor.clear
    tableView.frame = CGRect(x: 0, y: 100, width: UIScreen.width, height: UIScreen.noNavBarHeight - 100 - 10)
    tableView.delegate = self
    tableView.dataSource = self
    tableView.separatorStyle = .none
    tableView.register(InspectionCell.self, forCellReuseIdentifier: InspectionCell.identifier)
    let headerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 4))
    headerView.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.tableHeaderView = headerView
    
    tableView.mj_header = CustomRefreshHeader(refreshingBlock: { [weak self] in self?.headerRefresh() })
    
    view.addSubview(tableView)
  }
}

// MARK: - SJCalendarDelegete

extension PatrolInspectionVC: SJCalendarDelegete {
  
  func didSelected(date: Date) {
    currentDate = date
    pullData()
  }
  
}

// MARK: - UITableViewDataSource

extension PatrolInspectionVC : UITableViewDataSource {
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return inspections.count
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: InspectionCell.identifier) as! InspectionCell
    cell.model = inspections[indexPath.row]
    return cell
  }
}

// MARK: - UITableViewDelegate

extension PatrolInspectionVC : UITableViewDelegate {
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return InspectionCell.height(with: inspections[indexPath.row])
  }
  
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let model = inspections[indexPath.row]
    
    let vc = InspectionDetailVC()
    vc.status = model.status
    vc.isCooperate = model.cooperate
    vc.selectDate = currentDate
    vc.inspectionTime = model.timeInterval
    vc.isFromHome = false
    
    if vc.status == "WaitInspection" {
        vc.recordId = inspections[indexPath.row].planId }
    else {
        vc.recordId = inspections[indexPath.row].recordId }
    navigationController?.pushViewController(vc, animated: true)
  }
  
  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    
    let fixView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 1))
    fixView.backgroundColor = GlobalConfig.BGWhiteColor
    return fixView
    
  }
  
  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 1
  }

  
}
